@page "/visitor/visitorrequest"
@using Blazor.Server.UI.Services
@using CleanArchitecture.Blazor.Application.Features.Visitors.Commands.Create
@using CleanArchitecture.Blazor.Application.Features.Visitors.DTOs
@using CleanArchitecture.Blazor.Application.Features.Visitors.Queries.Search
@using CleanArchitecture.Blazor.Domain.Entities
@using CleanArchitecture.Blazor.Domain.Events
@using HashidsNet
@using Net.Codecrete.QrCodeGenerator
@attribute [Authorize(Policy = Permissions.Visitors.VisitorRequest)]
<PageTitle>@Title</PageTitle>
@inject IStringLocalizer<Visitors> L
<MudContainer MaxWidth="MaxWidth.Large">
    <ErrorBoundary>
        <ChildContent>
            <MudText Typo="Typo.h6">@L["Visitor Request"]</MudText>
            <MudText Typo="Typo.body1">@L["After submitting the application, visitors will receive SMS messages and fill in visitor information and upload necessary attachments or photos as prompted"]</MudText>
            <MudPaper Class="pa-4 mt-4">
                <MudForm Model="model" @ref="form" Validation="@(modelValidator.ValidateValue)">
                    <MudGrid>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTextField Label="@L["Visitor's Name"]"
                                          For="@(() => model.Name)"
                                          Required="true"
                                          RequiredError="@L["Visitor's name is required!"]"
                                          Disabled="@(model.Apppoved==true)"
                                          Adornment="Adornment.End"
                                          AdornmentIcon="@Icons.Material.Filled.Search"
                                          AdornmentColor="Color.Primary"
                                          OnAdornmentClick="SearchVisitors"
                                          @bind-Value="model.Name"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="8">
                            <MudTextField Label="@L["Company Name"]"
                                          For="@(() => model.CompanyName)"
                                          Disabled="@(model.Apppoved==true)"
                                          @bind-Value="model.CompanyName"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTextField Label="@L["License Plate Number"]"
                                          For="@(() => model.LicensePlateNumber)"
                                          Disabled="@(model.Apppoved==true)"
                                          @bind-Value="model.LicensePlateNumber"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTextField Label="@L["Email"]"
                                          For="@(() => model.Email)"
                                          Disabled="@(model.Apppoved==true)"
                                          @bind-Value="model.Email"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTextField Label="@L["Phone Number"]"
                                          For="@(() => model.PhoneNumber)"
                                          Disabled="@(model.Apppoved==true)"
                                          Required="true"
                                          RequiredError="@L["Phone Number is required!"]"
                                          @bind-Value="model.PhoneNumber"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTextField Label="@L["Identification No."]"
                                          For="@(() => model.IdentificationNo)"
                                          Disabled="@(model.Apppoved==true)"
                                          Required="true"
                                          RequiredError="@L["Identification No. is required!"]"
                                          @bind-Value="model.IdentificationNo"></MudTextField>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <PicklistAutocomplete Picklist="Picklist.Gender"
                                                  Disabled="@(model.Apppoved==true)"
                                                  Label="@L["Gender"]"
                                                  For="@(() => model.Gender)"
                                                  ResetValueOnEmptyText="true"
                                                  @bind-Value="model.Gender"></PicklistAutocomplete>
                        </MudItem>

                        <MudItem xs="12" sm="6" md="4">
                            <PicklistAutocomplete Picklist="Picklist.Purpose"
                                                  Label="@L["Purpose"]"
                                                  Disabled="@(model.Apppoved==true)"
                                                  Required="true"
                                                  RequiredError="@L["purpose is required!"]"
                                                  For="@(() => model.Purpose)"
                                                  ResetValueOnEmptyText="true"
                                                  @bind-Value="model.Purpose"></PicklistAutocomplete>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <EmployeeAutocomplete Label="@L["Select Employee"]"
                                                  Required="true"
                                                  Disabled="@(model.Apppoved==true)"
                                                  RequiredError="@L["employee is required!"]"
                                                  For="@(() => model.EmployeeId)"
                                                  ResetValueOnEmptyText="true"
                                                  @bind-Value="model.EmployeeId"></EmployeeAutocomplete>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudDatePicker Label="@L["Expected Date"]"
                                           Disabled="@(model.Apppoved==true)"
                                           Required="true"
                                           RequiredError="@L["expected date is required!"]"
                                           For="@(() => model.ExpectedDate)"
                                           @bind-Date="model.ExpectedDate"></MudDatePicker>
                        </MudItem>
                        <MudItem xs="12" sm="6" md="4">
                            <MudTimePicker Label="@L["Expected Time"]"
                                           Required="true"
                                           Disabled="@(model.Apppoved==true)"
                                           RequiredError="@L["expected time is required!"]"
                                           AmPm="true" TimeFormat="h:mm tt"
                                           For="@(() => model.ExpectedTime)"
                                           @bind-Time="model.ExpectedTime"></MudTimePicker>
                        </MudItem>
                        <MudItem xs="12" sm="12">
                            <Blazor.Server.UI.Pages.Sites.SiteWithAddressAutocomplete Label="@L["Select Site - Address"]"
                                                                                   Disabled="@(model.Apppoved==true)"
                                                                                   For="@(() => model.SiteId)"
                                                                                   Required="true" RequiredError="@L["site - address is required!"]"
                                                                                   @bind-Value="model.SiteId">
                            </Blazor.Server.UI.Pages.Sites.SiteWithAddressAutocomplete>
                        </MudItem>
                        <MudItem xs="12" sm="12">
                            <MudTextField Label="@L["Comment"]"
                                          For="@(() => model.Comment)"
                                          Lines="2"
                                          Disabled="@(model.Apppoved==true)"
                                          @bind-Value="model.Comment"></MudTextField>
                        </MudItem>
                    </MudGrid>
                </MudForm>
            </MudPaper>
            <MudPaper Class="d-flex pa-4 mt-4">
                <MudButton Variant="Variant.Filled" Color="MudBlazor.Color.Secondary" DisableElevation="true" OnClick="Reset" Class="ml-auto mx-2">@L["Reset"]</MudButton>
                <MudButton Disabled="@(_submiting)" Variant="Variant.Filled" OnClick="Submit" Color="MudBlazor.Color.Primary">
                    @if (_submiting)
                    {
                        <MudProgressCircular Class="ms-n1" Size="MudBlazor.Size.Small" Indeterminate="true" />
                        <MudText Class="ms-2">@L["Processing"]</MudText>
                    }
                    else
                    {
                        <MudText>@L["Submit"]</MudText>
                    }
                </MudButton>
            </MudPaper>
        </ChildContent>
        <ErrorContent>
            <CustomError Exception="context"></CustomError>
        </ErrorContent>
    </ErrorBoundary>
</MudContainer>
@code {
    public bool _submiting;
    public string Title = "visitor request";
    private MudForm form = default!;
    private VisitorRequestCommandValidator modelValidator = new();
    private VisitorRequestCommand model { get; set; } = new();
    [Inject]
    private ISender _mediator { get; set; } = default!;
    [Inject]
    private IPublisher _publisher { get; set; } = default!;
    [Inject]
    private Hashids hashids { get; set; } = default!;
    [Inject]
    private IUploadService _uploadService { get; set; } = default!;
    [Inject]
    private NavigationManager _navigationManager { get; set; } = default!;
    protected override async Task OnInitializedAsync()
    {
        Title = L["visitor request"];
        model.PassCode = hashids.EncodeLong(DateTime.Now.Ticks);
    }
    private async Task SearchVisitors()
    {

        var parameters = new DialogParameters {
                 { nameof(_QuickSearchDialog.keyword),model.Name },
            };
        var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true };
        var dialog = DialogService.Show<_QuickSearchDialog>
        (L["Quick Search Visitors"], parameters, options);
        var state = await dialog.Result;
        if (!state.Cancelled)
        {
            var dto = state.Data as VisitorDto;
            if (dto is not null)
            {
                model.Name = dto.Name;
                model.CompanyName = dto.CompanyName;
                model.Email = dto.Email;
                model.PhoneNumber = dto.PhoneNumber;
                model.LicensePlateNumber = dto.LicensePlateNumber;
                model.Gender = dto.Gender;
                model.IdentificationNo = dto.IdentificationNo;
            }
        }
    }
    private Task Reset()
    {

        model = new();
        model.PassCode = hashids.EncodeLong(DateTime.Now.Ticks);
        return Task.CompletedTask;
    }
    private async Task Submit()
    {
        _submiting = true;
        try
        {
            await form.Validate();
            if (form.IsValid)
            {
                await this.generateQrCode();
                var result = await _mediator.Send(model);
                model.Id = result.Data;
                Snackbar.Add(L["Submit successfully"], MudBlazor.Severity.Info);
                _navigationManager.NavigateTo("/visitor/visitors");
            }
        }
        finally
        {
            _submiting = false;
        }


    }
    private async Task generateQrCode()
    {
        var qr = QrCode.EncodeText(model.PassCode, QrCode.Ecc.Medium);
        var qrcode = qr.ToPng(12, 4);
        var result = await _uploadService.UploadAsync(new UploadRequest()
            {
                Data = qrcode,
                FileName = "Q_" + Guid.NewGuid().ToString() + ".png",
                Extension = ".png",
                Folder = model.PassCode,
                UploadType = UploadType.VisitorPricture
            });
        model.QrCode = result.Replace("\\", "/");
    }
}
